import React, { Component } from 'react';
import autoBind from 'react-autobind';
import { Link, browserHistory } from 'dva/router';
import { NavBar, Icon, Toast, TextareaItem } from 'antd-mobile';
import { createForm } from 'rc-form';

import { getUserId } from '../../../utils/utils';

// style
import styles from './index.css';
import IconfontStyle from '../../../assets/iconfont/iconfont.css';

// utils 
import dataCenter from '../../../utils/dataCenter'

class OrderBody extends Component {
	constructor(props) {
        super(props)
        autoBind(this)
    }
    componentDidMount() {
    	const { dispatch } = this.props
    	dispatch({
    		type: 'address/fetchAddress',
    		payload: getUserId()
    	})
    }
    getCheckedGoods() {
    	let checkedGoods = []
    	dataCenter.buycar.fullStore.map(store => {
    		store.goodsList.map(good => {
    			if(good.checked) {
    				checkedGoods.push(good)
    			}
    		})
    	})
    	return checkedGoods
    }
    getSelectedAddress() {
    	const { address } = this.props
    	let selectedAddress = null 

    	address.addressList && address.addressList.map(ad => {
    		if(ad.isDefault) {
    			selectedAddress = ad
    		}
    	})
    	selectedAddress = dataCenter.address && dataCenter.address.selected ? dataCenter.address.selected : selectedAddress

    	if(!selectedAddress) {
    		if(address.addressList.length) {
    			selectedAddress = address.addressList[0]
    		}
    	}
    	return selectedAddress
    }

    checkOrder(searchParam) {
    	if(!(searchParam.addressId)) {
    		Toast.info('请选择收货地址!', 1)
    		return false
    	}
    	if(!searchParam.shippingId) {
    		Toast.info('请选择运送方式!', 1);
    		return false
    	}
    	if(!searchParam.bestTime && !searchParam.bestTime == '0') {
    		Toast.info('请选择运送时间!', 1)
    		return false
    	}
    	if(!searchParam.cartIds.length) {
    		Toast.info('请选择至少一个商品!', 1)
    		return false
    	}
    	return true
    }
    onSubmitOrder() {
    	const { dispatch, address } = this.props
    	let totalPrice = 0
    	let cartIds = []
    	let selectedAddress = this.getSelectedAddress()
    	let checkedGoods = this.getCheckedGoods()
    	
    	checkedGoods.map(good => {
			totalPrice += parseFloat((good.goodsPrice * good.number).toFixed(2))
			cartIds.push(good.cartId)
		})
    	let searchParam = {
			userId: getUserId(),
			addressId: selectedAddress && selectedAddress.addressId,
			shippingId: dataCenter.shipping.shippingId,
			bestTime: dataCenter.shipping.timeType,
			postscript: dataCenter.order.remark,
			cartIds: cartIds.join(','),
			goodsAmount: totalPrice,
			shippingFee: dataCenter.shipping.shippingFee,
			orderAmount: String(totalPrice + dataCenter.shipping.shippingFee)
		}
		if(this.checkOrder(searchParam)) {
			dispatch({
	    		type: 'order/submitOrder',
	    		payload: {
	    			searchParam,
	    			callback: () => {
	    				dataCenter.shipping = null
	    				dataCenter.address = null
	    				dataCenter.order.remark = null
	    			}
	    		}
	    	})	
		}
    }
    onRemarkChange(value) {
    	dataCenter.order.remark = value

    	this.setState({
    		remark: value
    	})
    }
	render() {
		const { getFieldProps } = this.props.form;
		let totalPrice = 0

		let selectedAddress = this.getSelectedAddress()
		let checkedGoods = this.getCheckedGoods()
		checkedGoods.map(good => {
			totalPrice += parseFloat((good.goodsPrice * good.number).toFixed(2))
		})

	 	return (
	 		<div className={`${styles["order-body"]} order-body`}>
	 			<div className={styles["order-position-wrap"]}>
		 			<div className={styles["order-position"]} onClick={() => browserHistory.push('/address?fromPage=order')}>
		 				<div className={styles["order-position-top"]}>
		 					<span className={styles['order-position-name']}>{selectedAddress ? selectedAddress.consignee : '点击选择收货地址'}</span>
		 					<span className={styles["order-position-phone"]}>{selectedAddress && selectedAddress.mobile}</span>
		 					{
		 						selectedAddress && selectedAddress.isDefault ? (<span className={styles["order-position-tag"]}>默认</span>) : null
		 					}
		 				</div>
		 				<div className="order-position-detail">
		 					{
		 						selectedAddress ? (
		 							<i className={`${IconfontStyle['meyley-icon']} ${IconfontStyle['meyley-icon-location']}`} style={{fontSize: '0.4rem', color: '#999'}}/>
		 						) : <i className={`${IconfontStyle['meyley-icon']} ${IconfontStyle['meyley-icon-location']}`} style={{fontSize: '0.4rem', color: '#999', opacity: 0}}/>
		 					}
		 					
			 				<span className={styles["order-position-des"]}>{selectedAddress && selectedAddress.proviceName}{selectedAddress && selectedAddress.cityName}{selectedAddress && selectedAddress.districtName}{selectedAddress && selectedAddress.address}</span>
		 				</div>
		 				<i className={`${IconfontStyle['meyley-icon']} ${IconfontStyle['meyley-icon-right-arrow']}`} style={{fontSize: '0.4rem', color: '#999', position: 'absolute', top: '0.40rem', right: '0.20rem'}}/>
		 			</div>
	 			</div>

	 			<div className={styles["order-item"]} onClick={() => browserHistory.push('/deliverWay')}>
	 				<span className={styles["order-item-title"]}>
	 					配送方式
	 				</span>
	 				<span className={styles["order-item-value"]}>
	 					{
	 						dataCenter.shipping && dataCenter.shipping.shippingName ? (<span>已选择{dataCenter.shipping.shippingName}，{dataCenter.shipping.timeTypeName}送</span>): null
	 					}
	 				</span>
	 				<i className={`${IconfontStyle['meyley-icon']} ${IconfontStyle['meyley-icon-right-arrow']}`} style={{fontSize: '0.4rem', color: '#999', position: 'absolute', top: '0.16rem', right: '0.20rem'}}/>
	 			</div>

	 			<div className={styles["order-item-productions"]}>
	 				<div className={styles['order-item-productions-title']}>
	 					商品明细 <span>(共{checkedGoods.length}件)</span>
	 				</div>

	 				{
	 					checkedGoods.map((good, ii) => {
 							return (<div key={ii} className={styles["order-item-productions-item"]}>
	 							<img src={good.goodsThumb} className={styles['order-item-productions-img']} />
	 							<div className={styles['order-item-productions-right']} >
	 								<div className={styles['order-item-productions-sub-title']} >
	 								{good.goodsName}
	 								</div>
	 								<div className={styles['order-item-productions-des']} >
	 								{good.goodsAttrs}
	 								</div>
	 								<div className={styles['order-item-productions-money']}>
	 									<span style={{color: 'rgba(255,0,82,1)', marginRight: '0.42rem'}}>￥{good.goodsPrice}</span>
	 									<span style={{marginRight: '0.42rem'}}>x{good.number}</span>
	 								</div>
	 							</div>
	 						</div>)
	 					})
	 				}
	 			</div>
	 			{
	 				dataCenter.shipping && dataCenter.shipping.shippingFee ? (
	 					<div className={styles["order-item"]} onClick={() => browserHistory.push('/deliverWay')}>
			 				<span className={styles["order-item-title"]}>
			 					配送费用
			 				</span>
			 				<span className={styles["order-item-value"]}>
			 					{
			 						<span>{dataCenter.shipping.shippingFee}元</span>
			 					}
			 				</span>
			 			</div>
	 					) : null
	 			}

	 			<div style={{paddingBottom: '0.06rem'}}>
	 				<TextareaItem
				        autoHeight
	 					className={styles['order-item-input-remark']}
				        title="备注留言："
				        placeholder="请输入备注留言"
	 					onChange={this.onRemarkChange}
	 					value={dataCenter.order.remark}
				      />
	 			</div>

	 			<div className={styles['order-item-controll']}>
	 				<span>合计：<span style={{color: 'rgba(255,0,82,1)'}}>￥{totalPrice}</span></span>
	 				<span onClick={this.onSubmitOrder} className={styles['order-item-controll-button']}>提交订单</span>
	 			</div>
	 		</div>
	  	);
	}
};

OrderBody.propTypes = {
};

export default createForm()(OrderBody);
